package com.chengshi.shop.controller.admin.order;

import com.chengshi.shop.controller.common.BaseController;
import com.chengshi.shop.model.member.Member;
import com.chengshi.shop.model.order.Order;
import com.chengshi.shop.model.order.OrderHistory;
import com.chengshi.shop.model.order.OrderItem;
import com.chengshi.shop.model.order.OrderPayment;
import com.chengshi.shop.model.system.Express;
import com.chengshi.shop.service.express.ExpressService;
import com.chengshi.shop.service.member.MemberService;
import com.chengshi.shop.service.order.OrderHistoryService;
import com.chengshi.shop.service.order.OrderItemService;
import com.chengshi.shop.service.order.OrderPaymentService;
import com.chengshi.shop.service.order.OrderService;
import com.chengshi.shop.util.EnumUtil;
import com.chengshi.shop.util.MessageUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 商城订单相关
 *
 * @author xuxinlong
 * @version 2017年10月11日
 */
@RestController
@RequestMapping("/admin/order")
public class OrderController extends BaseController {
    @Resource
    private OrderService orderService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private OrderPaymentService orderPaymentService;
    @Resource
    private MemberService memberService;
    @Resource
    private ExpressService expressService;
    @Resource
    private OrderHistoryService orderHistoryService;

    @Value("${wechat.mp.host}")
    private String host;


    /**
     * 订单列表页面
     *
     * @return
     */
    @GetMapping(value = "orderList")
    public ModelAndView orderList(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("admin/order/orderList");
        mav.addObject("memberId", request.getParameter("memberId"));
        mav.addObject("status", request.getParameter("status"));
        return mav;
    }

    /**
     * 订单详情页面
     *
     * @return
     */
    @GetMapping(value = "orderDetail")
    public ModelAndView orderDetail(@RequestParam Integer orderId) throws Exception{
        ModelAndView mav = new ModelAndView("admin/order/orderDetail");
        Order order = orderService.getOrderByOrderId(orderId);
        Member member = memberService.getMemberByMemberId(order.getMemberId());
        order.setMemberName(member.getName());
        List<OrderItem> orderItemList = orderItemService.getListByOrderId(orderId);
        List<OrderHistory> historyList = orderHistoryService.getListByOrderId(orderId);
        List<OrderPayment> paymentList = orderPaymentService.getOrderPaymentList(orderId);
        if (!paymentList.isEmpty()){
            order.setPaymentMethod(EnumUtil.getName("PAYMENT_METHOD", paymentList.get(0).getPaymentMethod()));
        }
        mav.addObject("order", order);
        mav.addObject("orderItemList", orderItemList);
        mav.addObject("historyList", historyList);
        mav.addObject("host", host);
        return mav;
    }

    /**
     * 获取订单列表
     *
     * @return
     */
    @GetMapping("/getOrderList")
    public PageInfo<Order> getOrderList(HttpServletRequest request) {
        this.startPage();
        HashMap<String, Object> inMap = new HashMap<>();
        inMap.put("status", request.getParameter("status"));
        inMap.put("startTime", request.getParameter("startTime"));
        inMap.put("endTime", request.getParameter("endTime"));
        inMap.put("orderNum", request.getParameter("orderNum"));
        inMap.put("memberId", request.getParameter("memberId"));
        List<Order> orderList = orderService.getOrderList(inMap);
        return new PageInfo<>(orderList);
    }

    /**
     * 后台关闭订单
     * @param orderId
     * @return
     */
    @PostMapping("/closeOrder")
    public HashMap<String, Object> closeOrder(@RequestParam Integer orderId){
        HashMap<String, Object> retMap = MessageUtils.success("关闭订单成功");
        try {
            Order order = orderService.getOrderByOrderId(orderId);
            if (order.getStatus() <= EnumUtil.ORDER_STATUS.待收货.getValue().byteValue()) {
                orderService.closeOrder(order, "系统", "商家关闭订单，交易关闭");
            } else {
                retMap = MessageUtils.error("订单已经不能关闭");
            }
        } catch (Exception e) {
            retMap = MessageUtils.error(e.getMessage());
        }
        return retMap;
    }

    /**
     * 订单发货页面
     * @param orderId
     * @return
     */
    @GetMapping("/deliveryForm")
    public ModelAndView deliveryForm(@RequestParam Integer orderId){
        ModelAndView mav = new ModelAndView("admin/order/deliveryForm");
        Order order = orderService.getOrderByOrderId(orderId);
        List<Express> expressList = expressService.getExpressList();
        mav.addObject("order", order);
        mav.addObject("expressList", expressList);
        return mav;
    }

    /**
     * 订单物流信息页面
     * @param orderId
     * @return
     * @throws Exception
     */
    @GetMapping("/orderHistoryForm")
    public ModelAndView orderHistoryForm(@RequestParam Integer orderId) throws Exception {
        ModelAndView mav = new ModelAndView("admin/order/orderHistoryForm");
        List<OrderHistory> historyList = orderHistoryService.getListByOrderId(orderId);
        mav.addObject("historyList", historyList);
        return mav;
    }

    /**
     * 订单开始发货
     * @param orderId
     * @param expressNum
     * @param expressCode
     * @return
     */
    @PostMapping("/saveOrderDelivery")
    public HashMap<String, Object> saveOrderDelivery(@RequestParam Integer orderId, @RequestParam String expressNum, @RequestParam String expressCode){
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            Order order = orderService.getOrderByOrderId(orderId);
            order.setExpressCode(expressCode);
            order.setExpressNum(expressNum);
            boolean status = order.getStatus() == EnumUtil.ORDER_STATUS.待发货.getValue().byteValue()
                    || (order.getStatus() == EnumUtil.ORDER_STATUS.待收货.getValue().byteValue() && !order.getIsSign());
            if (status) {
                orderService.saveOrderDelivery(order);
            } else {
                retMap = MessageUtils.error("该订单状态暂时无法操作");
            }
        } catch (Exception e) {
            retMap = MessageUtils.error(e.getMessage());
        }
        return retMap;
    }

}
